package com.tx.controller;

import cn.hutool.core.util.ObjectUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.tx.entity.User;
import com.tx.service.IUserService;
import com.tx.service.impl.MySecurityUserDetailServiceImpl;
import com.tx.util.AjaxResult;
import com.tx.util.UserCacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Controller
public class LoginController {

    @Autowired
    private IUserService userService;

    @Autowired
    private MySecurityUserDetailServiceImpl userDetailService;

    @Autowired
    private DefaultKaptcha defaultKaptcha;


    @GetMapping("/toLogin")
    public String toLogin(){
        return "/login";
    }


    @GetMapping("/captchaImage")
    public void captchaImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        byte[] captcha = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try {
            // 将生成的验证码保存在session中
            String createText = defaultKaptcha.createText();
            request.getSession().setAttribute("rightCode", createText);
            BufferedImage bi = defaultKaptcha.createImage(createText);
            ImageIO.write(bi, "jpg", out);
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        captcha = out.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream sout = response.getOutputStream();
        sout.write(captcha);
        sout.flush();
        sout.close();
    }


    @ResponseBody
    @PostMapping("/loginBody")
    public AjaxResult login(HttpServletRequest request,String username, String password, String captcha, int rememberMe) {



        User user = (User) userDetailService.loadUserByUsername(username);

        if (ObjectUtil.isNull(user)){
            return AjaxResult.error("用户或密码错误");
        }

        if (!user.getPassword().equals(password)){
            return AjaxResult.error("用户或密码错误");
        }

        //用户登录成功，保持会话
        //创建缓存，默认1个小时过期
        String sessionId = request.getSession().getId();
        UserCacheUtil.addUser(sessionId,user);

        return AjaxResult.success();
    }

}
